/**
 *@description: 网络类的封装
 *@author: jsyang
 *@date: 2021-06-03 13:56:31
*/
declare var window:any
export default async (url = '', data = {}, type = 'GET', method = 'fetch',responseType='') => {
    type = type.toUpperCase();
    url = url;

    if (type == 'GET') {
        let dataStr = ''; //数据拼接字符串
        Object.keys(data).forEach(key => {
            dataStr += key + '=' + data[key] + '&';
        })

        if (dataStr !== '') {
            dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
            url = url + '?' + dataStr;
        }
    }

    if (window.fetch && method == 'fetch') {
        let requestConfig = {
            credentials: 'include',
            method: type,
            headers: {
                'Accept': 'application/json',// 用户代理可处理的媒体类型// 用户代理可处理的媒体类型
                'Content-Type': 'application/json',// 报文主体对象类型,
                'Access-Control-Request-Private-Network': true // 专用网络标头
            },
            mode: "cors",// 跨域
            cache: "force-cache"
        }

        if (type == 'POST') {
            Object.defineProperty(requestConfig, 'body', {
                value: JSON.stringify(data)
            })
        }

        try {
            const response = await fetch(url, requestConfig as any);
            let responseText = await response.text();
            // const arrayBuffer = await response.arrayBuffer()
            try {
                responseText = JSON.parse(responseText)
            } catch (e) {

            }
            return responseText
        } catch (error) {
            throw new Error(error)
        }
    } else {
        // 如果浏览器不支持 fetch
        return new Promise((resolve, reject) => {
            let requestObj;
            if (window.XMLHttpRequest) {
                requestObj = new XMLHttpRequest();
            } else {
                requestObj = new window.ActiveXObject;
            }

            let sendData = '';
            if (type == 'POST') {
                sendData = JSON.stringify(data);
            }
            requestObj.open(type, url, true);
            if(responseType){
                requestObj.responseType = responseType; //blob也可以
            }
            requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            requestObj.setRequestHeader("Access-Control-Request-Private-Network", true);
            // requestObj.setRequestHeader("Access-Control-Expose-Headers","logincodeid")
            // requestObj.addHeader("logincodeid")
            requestObj.send(sendData);
            requestObj.onreadystatechange = () => {
                if (requestObj.readyState == 4) {
                    if (requestObj.status == 200) {
                        const logincodeid =  requestObj.getResponseHeader('logincodeid')
                        let obj = responseType ? requestObj.response : requestObj.responseText
                        if ( typeof obj !== 'object' ) {
                            obj = JSON.parse(obj);
                        }
                        responseType ? resolve({ data:obj, logincodeid }):resolve(obj)
                    } else {
                        reject(requestObj)
                    }
                }
            }
        })
    }
}
